package lib.bone.admin.controller.system;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.Validator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lib.bone.admin.anno.WebLog;
import lib.bone.admin.constant.MethodTypeConst;
import lib.bone.common.constant.ResponseCodeConst;
import lib.bone.common.core.domain.ResponseDTO;
import lib.bone.system.module.notify.domain.SysNotify;
import lib.bone.system.module.notify.domain.dto.NotifyQueryDTO;
import lib.bone.system.module.notify.service.SysNotifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

@Api(tags = "通知管理")
@RestController
@RequestMapping("system")
public class SysNotifyController {

    @Autowired
    SysNotifyService service;

    @WebLog(module = "bone-system")
    @PostMapping("notify")
    @ApiOperation(value = "新建通知")
    public ResponseDTO<Object> newNotify(@RequestParam("content") String content){
        if (Validator.isEmpty(content)) return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM,"参数不可为空");
        SysNotify notify = new SysNotify();
        notify.setContent(content);
        notify.setNotifyStatus(1);
        notify.setOperator(StpUtil.getLoginIdAsLong());
        return ResponseDTO.succData(service.saveOne(notify));
    }

    @WebLog(module = "bone-system",operate = MethodTypeConst.DELETE)
    @DeleteMapping("notify/{id}")
    @ApiOperation(value = "删除通知")
    public ResponseDTO<SysNotify> deleteNotify(@PathVariable("id") Long id){
        return service.deleteById(id);
    }

    @GetMapping("notify")
    @ApiOperation(value = "查询通知")
    public ResponseDTO<Object> getNotify(NotifyQueryDTO dto){
        Sort sort;
        if(dto.getOrder().equalsIgnoreCase("DESC")){
            sort = Sort.by(Sort.Direction.DESC, dto.getSortBy());
        }else {
            sort = Sort.by(Sort.Direction.ASC, dto.getSortBy());
        }

        // tips : 页码对应 - 1
        Pageable pageable = PageRequest.of(dto.getPageNum() - 1 , dto.getPageSize(), sort);
        SysNotify notify = new SysNotify();
        BeanUtil.copyProperties(dto,notify, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        Example<SysNotify> example = Example.of(notify);
        return ResponseDTO.succData(service.getAll(pageable,example));
    }

}
